
<template>
	<image :src="imgSrc" :mode="mode" @click="emitEvent" :class="className"></image>
</template>

<script>
	export default {
		props: {
			src: {
				type: String
			},
			mode: {
				type: String,
				default: 'aspectFill'
			},
			className: ''
		},
		data() {
			return {
				imgSrc: ''
			}
		},
		created() {
			this.getCacheImage(this.src).then(res=>{
				if(res.code === 1){
					this.imgSrc = res.data
				}else{
					this.imgSrc = this.src
				}
			}).catch(res=>{
				this.imgSrc = this.src
			})
		},
		methods: {
			emitEvent() {
				this.$emit('tapImg')
			},
			getCacheImage (url){
				if(!url || typeof url !== 'string'){
					return new Promise((resolve, reject)=>{reject({code: 0, msg: '图片地址不存在', data: url})})
				}
				if(!/(png|jpg|jpeg|gif|webp)$/.test(url)){
					return new Promise((resolve, reject)=>{reject({code: 0, msg: '图片格式不规范', data: url})})
				}
				if(/^http/.test(url)){
					let filename = '_doc/'
					filename += url.split('/').slice(-1).join()
					return new Promise ((resolve, reject) => {
						plus.io.resolveLocalFileSystemURL(filename, ( entry ) => {
							let path = plus.io.convertLocalFileSystemURL(filename);
							path = 'file://' + path
							resolve({code: 1, msg: '缓存读取成功', data: path})
						}, ()=> {
							this.createDownload(url, function(path){
								//resolve({code: 1, msg: '图片下载成功', data: path})
							})
							resolve({code: 1, msg: '首次返回原始图片', data: url})
						})
					})
				}else{
					return new Promise((resolve, reject)=>{reject({code: 0, msg: '图片地址错误', data: url})})
				}
			},
			createDownload(url) {
				let filename = '_doc/'
				filename += url.split('/').slice(-1).join()
				let dtask = plus.downloader.createDownload(url, {
					filename: filename
				}, function(d, status){
					if(status == 200){
						let path = plus.io.convertLocalFileSystemURL(d.filename);
						path = 'file://' + path
						//success(path)
					}else{
						//success({code: 0, msg: '图片下载失败', data: url})
					}  
				});
				dtask.start(); 
			}
		}
	}
</script>

<style>

</style>
